
const cache = JSON.parse(sessionStorage.staffStateCache || '{}')

const state = {
  currentStaffTab: '/',
  opendStaffTabs: Array.isArray(cache.opendStaffTabs) ? cache.opendStaffTabs : []
}

const types = {
  SET_STAFF_CURRENT_TAB: 'set_staff_current_tab',
  CLEAN_STAFF_TAB: 'clean_staff_tab',
  REMOVE_STAFF_TAB: 'remove_staff_tab',
  ADD_STAFF_TAB: 'add_staff_tab'
}

const mutations = {
  [types.SET_STAFF_CURRENT_TAB] (state, val) {
    state.currentStaffTab = val
  },
  [types.REMOVE_STAFF_TAB] (state, index) {
    state.opendStaffTabs.splice(index, 1)
    setStateCache(state)
  },
  [types.ADD_STAFF_TAB] (state, staff) {
    state.opendStaffTabs = [...state.opendStaffTabs, staff]
    setStateCache(state)
  },
  [types.CLEAN_STAFF_TAB] (state) {
    state.currentStaffTab = '/'
    state.opendStaffTabs = []
  }
}

const actions = {
  setStaffCurrentTab ({ commit }, val) {
    commit(types.SET_STAFF_CURRENT_TAB, val)
  },
  addStaffTab ({ commit, state }, staff) {
    return new Promise(resolve => {
      commit(types.SET_STAFF_CURRENT_TAB, '/' + staff.id)
      const staffIds = state.opendStaffTabs.map(staff => staff.id)
      if (!staffIds.includes(staff.id)) {
        commit(types.ADD_STAFF_TAB, staff)
      }
      resolve()
    })
  },

  removeStaffTab ({ commit, dispatch, state }, id) {
    return new Promise(resolve => {
      let lastTabId
      let _id = id.replace('/', '')

      state.opendStaffTabs.forEach((tab, index) => {
        if (tab.id === _id) {
                    // eslint-disable-line
          lastTabId = (state.opendStaffTabs[index - 1] && state.opendStaffTabs[index - 1].id) || ''
          commit(types.REMOVE_STAFF_TAB, index)
        }
      })
      resolve('/' + lastTabId)
    })
  },

  cleanStaffStateCache ({ commit }) {
    return new Promise(resolve => {
      cleanStateCache()
      commit(types.CLEAN_STAFF_TAB)
      resolve()
    })
  },

  getStaffByUrl ({ dispatch, state }, data) {
    // console.log(data.target)
    if (data.target && !hasKey(state.opendStaffTabs, data.target)) {
            const staff = data.staffs.filter(staff => staff.id == data.target)[0]; // eslint-disable-line
      dispatch('addStaffTab', staff)
    }
  }
}

const getters = {
  // currentStaffTab: state => state.currentStaffTab,
  opendStaffTabs: state => state.opendStaffTabs
}

function setStateCache (state) {
  const cache = {
    currentStaffTab: state.currentStaffTab,
    opendStaffTabs: state.opendStaffTabs
  }
  sessionStorage.setItem('staffStateCache', JSON.stringify(cache))
}

function cleanStateCache () {
  sessionStorage.setItem('staffStateCache', JSON.stringify({}))
}

function hasKey (arr, id) {
    return arr.filter(item => item == id)[0]; // eslint-disable-line
}

export default {
  state,
  getters,
  mutations,
  actions
}
